package com.lr.transfer.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.google.code.kaptcha.Constants;
import com.lr.transfer.config.HttpHandle;
import com.lr.transfer.config.TransferProperties;
import com.lr.transfer.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.jodconverter.DocumentConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 用户控制器.
 */
@RestController
@Slf4j
public class TransferController extends BaseController {

    @Autowired
    private TransferProperties gunsProperties;
    // @Autowired
    private DocumentConverter documentConverter;


    /**
     * 查询所用用户
     *
     * @return
     */
    @GetMapping("/lr")
    public ModelAndView toTransfer(Model model) {
        model.addAttribute("title", "转换web");
        if (gunsProperties.getKaptchaOpen()) {
            model.addAttribute("open", "true");
        }
        return new ModelAndView("transfer", "model", model);
    }

    @GetMapping("/lr/transfer")
    public ModelAndView transferGet(Model model) {
        model.addAttribute("title", "PDF/Word 转换");
        if (gunsProperties.getKaptchaOpen()) {
            model.addAttribute("open", "true");
        }
        return new ModelAndView("transfer", "model", model);
    }

    /**
     * 方法描述:图片转换成Base64
     *
     * @param: [model, file]
     * @author liran
     * @date 2018/9/29 13:25
     */
    @PostMapping(value = "/lr/transferImage")
    public ModelAndView transfer(Model model, MultipartFile file) throws Exception {
        String suffix = ToolUtil.getFileSuffix(file.getOriginalFilename());
        if (StringUtils.isBlank(suffix)) {
            throw new Exception("未检测到图片");
        }
        if (StringUtils.equals("jpg", suffix) || StringUtils.equals("jpeg", suffix)
                || StringUtils.equals("png", suffix) || StringUtils.equals("gif", suffix)) {
            model.addAttribute("isSuccess", "生成成功");
            String base64 = Base64TransferUtil.GetImageStr(file.getInputStream());
            model.addAttribute("base64", base64);
            model.addAttribute("originBase64", true);
            return new ModelAndView("success", "model", model);
        } else {
            throw new Exception("不支持此图片格式：" + suffix + "");
        }
    }


    /**
     * 转换PDF/WORD
     */
    @PostMapping(value = "/lr/transfer")
    public ModelAndView transfer(Model model, MultipartFile file, Integer type) {
        model.addAttribute("originMD5", false);

        //验证验证码是否正确
        if (KaptchaUtil.getKaptchaOnOff()) {
            String kaptcha = super.getPara("kaptcha").trim();
            String code = (String) super.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
            if (ToolUtil.isEmpty(kaptcha) || !kaptcha.equalsIgnoreCase(code)) {
                model.addAttribute("isSuccess", "验证码有误");
                return new ModelAndView("success", "model", model);
            }
        }
        String suffix = ToolUtil.getFileSuffix(file.getOriginalFilename());
        String pictureName = UUID.randomUUID().toString() + "." + suffix;
        try {
            String time = new SimpleDateFormat("yyyyMMdd").format(new Date());
            String fileSavePath = TransferProperties.fileUploadPath + time + "/";
            String fileLocalSavePath = fileSavePath + pictureName;
            FileUtils.writeByteArrayToFile(new File(fileLocalSavePath), file.getBytes());

            log.info("保存的文件路径--> fileLocalSavePath:{}", fileLocalSavePath);
            if (type == 0 && (StringUtils.equals("doc", suffix) || StringUtils.equals("docx", suffix))) {
//                //word 转换为pdf 方法一
//                String local_path = OfficeToPdfUtil.officeToPdf(fileLocalPath);

                //word 转换pdf 方法2
                String newTime = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
                String local_path = fileSavePath + newTime + "lr.pdf";
                try {
                    File inputFile = new File(fileLocalSavePath);
                    File outputFile = new File(local_path);
                    documentConverter.convert(inputFile).to(outputFile).execute();
                } catch (Exception e) {
                    log.error("转换错误------------> Exception:{}", e);
                    throw e;
                }
                log.info("word 转换为pdf 后的本地路径地址：{}", local_path);
                String view_path = StringUtils.substringAfter(local_path, TransferProperties.fileUploadPath);
                log.info("word 转换为pdf 后的访问地址：{}", view_path);
                model.addAttribute("view_path", "downLoad?filename=" + view_path);
                model.addAttribute("isSuccess", "转换成功");
            } else if (StringUtils.equals("pdf", suffix)) {
                //pdf 转换为img
                List<String> getImg = PdfToImageUtil.pdfToIamge(fileLocalSavePath);
                if (getImg == null) {
                    model.addAttribute("isSuccess", "转换失败");
                } else {
                    model.addAttribute("isSuccess", "转换成功");
                    List<File> fileList = new ArrayList<>(getImg.size());
                    for (String img : getImg) {
                        File oneFile = new File(img);
                        if (!oneFile.isDirectory() && oneFile.exists())
                            log.info("pdf转换图片路径地址：{}", oneFile);
                        fileList.add(oneFile);
                    }
                    // ZipUtil.writeZip(getHttpServletRequest(), getHttpServletResponse(),fileList,"pdfToImages");
                }
            } else {
                model.addAttribute("isSuccess", "转换类型暂时不支持");
            }
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("isSuccess", "转换异常：" + e);
            return new ModelAndView("success", "model", model);
        }
        return new ModelAndView("success", "model", model);
    }


    @GetMapping("/lr/MD5")
    public ModelAndView MD5(Model model) {
        model.addAttribute("currentTimeMillis", System.currentTimeMillis());
        return new ModelAndView("MD5", "model", model);
    }

    @Autowired
    HttpHandle httpHandle;

    @PostMapping("/lr/MD5Transfer")
    public ModelAndView MD5(Model model, String localUrl, String userCode, String timestamp, String publicKeyCode, String jsonContent, HttpSession session) throws Exception {
        model.addAttribute("originMD5", true);

        log.info("userCode:{}", userCode);
        log.info("timestamp:{}", timestamp);
        log.info("publicKeyCode:{}", publicKeyCode);
        log.info("jsonContent:{}", jsonContent);


        String newJsonContent = jsonContent;
        if (StringUtils.isBlank(userCode) || StringUtils.isBlank(timestamp) || StringUtils.isBlank(publicKeyCode)) {
            model.addAttribute("isSuccess", "输入的转换参数不能为空");
            model.addAttribute("md5Value", "NO_RESULT");
        } else {
            boolean isJson = false;
            try {
                JSONObject jsonObject = JSON.parseObject(jsonContent);
                isJson = true;
            } catch (Exception e) {
                log.info("输入的JSON 参数有误");
                throw new JSONException("JSON 格式有误，请检查JSON参数；错误信息：" + e.getMessage());
            }
            if (isJson) {
                jsonContent = jsonContent.replaceAll("\n", "");
                jsonContent = jsonContent.replaceAll("\r", "");
                //jsonContent=getJsonContent(jsonContent);

                userCode = userCode.trim();
                publicKeyCode = publicKeyCode.trim();
                timestamp = timestamp.trim();

                String value = userCode + publicKeyCode + timestamp + jsonContent;
                String md5Value = MD5Util.MD5Encoder(value);
                log.info("转换后的md5:{}", md5Value);
                model.addAttribute("isSuccess", "生成签名成功");

                model.addAttribute("localUrl", localUrl);
                model.addAttribute("userCode", userCode);
                model.addAttribute("timestamp", timestamp);
                model.addAttribute("publicKeyCode", publicKeyCode);
                model.addAttribute("jsonContent", newJsonContent);
                model.addAttribute("md5Value", md5Value);
                String postManHeader = "Content-Type:application/json\n" +
                        "usercode:" + userCode + "\n" +
                        "utime:" + timestamp + "\n" +
                        "sign:" + md5Value;

                //放入session 中
                session.setAttribute("userCode", userCode);
                session.setAttribute("publicKeyCode", publicKeyCode);
                session.setAttribute("jsonContent", newJsonContent);

                model.addAttribute("postManHeader", postManHeader);

            }
        }
        if (StringUtils.isNotBlank(localUrl)) {
            return new ModelAndView("ajax", "model", model);
        }
        return new ModelAndView("success", "model", model);
    }


    /**
     * 获取json请求
     *
     * @return
     */
    public String readJSONString(BufferedReader br) {
        StringBuffer json = new StringBuffer();
        String line = null;
        try {
            while ((line = br.readLine()) != null) {
                json.append(line);
            }
        } catch (Exception e) {
            System.out.println(e.toString());
        }
        return json.toString();
    }


//
//    public String getJsonContent(String json) throws Exception {
//        String time = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
//        String fileSavePath = TransferProperties.fileUploadPath + time + "/";
//        // String fileLocalPath = fileSavePath + pictureName;
//        String pathname = fileSavePath + time + ".txt"; // 绝对路径或相对路径都可以，这里是绝对路径，写入文件时演示相对路径
//
//        /* 写入Txt文件 */
//        File writename = new File(pathname); // 相对路径，如果没有则要建立一个新的output。txt文件
//        //先得到文件的上级目录，并创建上级目录，在创建文件
//        writename.getParentFile().mkdir();
//        writename.createNewFile(); // 创建新文件
//        BufferedWriter out = new BufferedWriter(new FileWriter(writename));
//        out.write(json); // \r\n即为换行
//        out.flush(); // 把缓存区内容压入文件
//        out.close(); // 最后记
//
//
//        File filename = new File(pathname); // 要读取以上路径的input。txt文件
//        InputStreamReader reader = new InputStreamReader(
//                new FileInputStream(filename));
//        BufferedReader br = new BufferedReader(reader); // 建立一个对象，它把文件内容转成计算机能读懂的语言
////        String line = "";
////        line = br.readLine();
////        while (line != null) {
////            line = br.readLine(); // 一次读入一行数据
////        }
//        String jsonContent = httpHandle.readJSONString(br);
//        return jsonContent;
//    }


}
